from rest_framework import status
from rest_framework.response import Response
from rest_framework.viewsets import ModelViewSet

from apps.system.models import Images
from apps.system.serializers.images import ImagesSerializer

from apps.utils.utils import create_file


class ImagesView(ModelViewSet):
    queryset = Images.objects.all()
    serializer_class = ImagesSerializer

    def create(self, request, *args, **kwargs):
        file = request.data.get('file')
        if not file:
            return Response({'msg': '文件不能为空'}, status=status.HTTP_400_BAD_REQUEST)

        size = file.size  # 获取图片大小
        name = file.name  # 获取图片名称
        file_type = file.content_type  # 获取图片类型

        file_type_list = ['image/png', 'image/jpeg', 'image/jpg', 'image/gif', 'image/bmp', 'image/webp', 'image/svg']
        if size > 1024 * 2000:
            return Response({'msg': '图片大小不能超过2mb！您的图片大小为：{}kb'.format(round(size / 1024))},
                            status=status.HTTP_400_BAD_REQUEST)
        elif file_type not in file_type_list:
            return Response({'msg': '您上传的文件类型不合格！'}, status=status.HTTP_400_BAD_REQUEST)
        else:
            new_file = create_file(file)
            if not new_file:
                return Response({'msg': '图片上传失败！'}, status=status.HTTP_400_BAD_REQUEST)

            if request.data.get('name'):
                name = request.data.get('name')
            else:
                name = name.replace('.' + name.split('.')[-1], "")

            save_data = {
                'name': name,
                'size': size,
                'file': new_file[0]
            }
            serializer = self.get_serializer(data=save_data)
            serializer.is_valid(raise_exception=True)
            self.perform_create(serializer)
            data = serializer.data
            data['img_url'] = new_file[1]
            headers = self.get_success_headers(data)
            return Response(data, status=status.HTTP_201_CREATED, headers=headers)
